package com.yz.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yz.common.pojo.ResultCode;
import com.yz.zuul.FeignClients.LoginFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 钰杰
 */
@Component
public class MyFilter extends ZuulFilter {

    @Autowired
    private LoginFeignClient loginFeignClient;

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    @Override
    //控制过滤器是否生效  true为生效
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();
//        String authorization = ctx.getRequest().getHeader("Authorization");
//        if (authorization == null || "".equals(authorization)) {
//            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(ResultCode.ERROR_NO_TOKEN_CODE);
//        }
        int auth = checkAuth();
        if (auth == 0 || "0".equals(auth)) {
            ctx.setSendZuulResponse(true);//成功
            ctx.setResponseStatusCode(ResultCode.SUCCESS_CODE);
        } else if (auth == 1 || "1".equals(auth)) {
            ctx.setSendZuulResponse(false);//无权
            ctx.setResponseStatusCode(ResultCode.ERROR_NO_AUTHORIZATION_CODE);
        } else if (auth == 2 || "2".equals(auth)) {
            ctx.setSendZuulResponse(false);//token过期
            ctx.setResponseStatusCode(ResultCode.ERROR_TOKEN_EXCEEDED_CODE);
        } else if (auth == 3 || "3".equals(auth)) {
            ctx.setSendZuulResponse(false);//无token
            ctx.setResponseStatusCode(ResultCode.ERROR_NO_TOKEN_CODE);
        }
        return null;
    }


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 3 无token
     * 2 jwt过期
     * 1 游客无权
     * 0 成功
     *
     * @return
     */
    public int checkAuth() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        //获取token
        String accessToken = request.getHeader("Authorization");

        //无toke或者过期，
        if (accessToken == null || "".equals(accessToken)) {
            log.warn("token is empty");
            return 3;   //无token
        } else {
            //请求URL
            String requestURL = request.getRequestURL().toString();
            //请求路由
            String routesPath = requestURL.substring(22, 27);
            //标识当前请求路由
            String auth = "";
            if (routesPath.contains("dba")) {
                auth = "DBA";
            } else if (routesPath.contains("admin")) {
                auth = "ADMIN";
            } else if (routesPath.contains("bi")) {
                auth = "BI";
            }

            //获取当前用户角色列表
            Map userRolesByToken = loginFeignClient.getUserRolesByToken(accessToken);
            Integer error = (Integer) userRolesByToken.get("error");
            if (null != error) {
                return 2;//错误信息
            }
            List<Map> userRolesByToken1 = (List<Map>) userRolesByToken.get("userRolesByToken");
            ArrayList<String> currentUserRoles = new ArrayList<>();
            for (Map role : userRolesByToken1) {
                currentUserRoles.add((String) role.get("authority"));
            }
            //当前请求 匹配 用户角色列表信息 ， 只要有就为TRUE ,没有就为false
            if (currentUserRoles.contains("ROLE_" + auth)) {
                return 0;   //成功权限
            }
            return 1;   //游客
        }

    }
}



